
<template>
  <div>
      <Row :gutter="5">
            <Col :span="6">
                <Card >
                    <div  slot="title" class="orgSearch" v-if="user_type!='02'">
                        <Input  type="text" v-model="searchValue" placeholder="服务商名称"></Input>
                        <Button type="primary" class="zh-hollow" @click="getTree" >搜索</Button>
                    </div>
                    <div style="overflowX:auto">
                        <Tree  v-for="(item ,index) in data " :key="index"  :data="item" @on-toggle-expand="toggleExpand" @on-select-change="selectChange"></Tree> 
                    </div>
                        
                </Card>
            </Col>
            <Col :span="18" >
                <Card v-if="uuid.length>0">
                    <div slot="title">
                        <p>{{superior}}的下属部门</p>
                        <Button v-if='btnp.fwsjgou_xzxsbm' @click="modal_add_part=true" type="primary" class="zh-hollow"  icon="plus-round">新增下属部门</Button>
                    </div>
                    <div style="min-height:150px;" v-if="uuid.length>0">
                        <p v-if="tableData.length<=0">该层级没有下属部门。</p>
                        <template v-else>
                            <Table  border :columns="columns" :data="tableData"></Table>
                            <Page  :current.sync="pageNumber" :total="total" show-total  @on-change="pageChange"></Page>
                        </template>
                        
                    </div>
                </Card>
            </Col>           
      </Row>
      <Modal :loading="addLoading" title="新增下属部门" v-model="modal_add_part" @on-ok="save('save')" ok-text="保存" cancel-text="放弃操作" >
            <Form  :label-width="80" style="padding:15px 30px;">
                <FormItem label="上级部门*">
                    <Input readonly v-model="superior" ></Input>
                </FormItem>
                <FormItem label="部门名称*">
                    <Input  v-model="partName" ></Input>
                </FormItem>
            </Form> 
      </Modal>
      <Modal :loading="editLoading" title="编辑部门信息" v-model="modal_edit_part" @on-ok="save('edit')" ok-text="保存" cancel-text="放弃操作" >
            <Form :model="editPart" :label-width="80" style="padding:15px 30px;">
                <FormItem label="上级部门*">
                    <Input readonly v-model="superior" ></Input>
                </FormItem>
                <FormItem label="部门名称*">
                    <Input  v-model="partName" ></Input>
                </FormItem>
                <FormItem label="部门主管*">
                    <p @click="modal_select_charge=true" style="color:#2D8CF0;cursor:pointer;">
                        <span v-if="editPart.proUuid.length>0">{{proNames}}</span>
                        <span v-else>选择</span>
                        
                    </p>
                    <p style="line-height:1.5em">主管可以登录管理后台查看和操作本级以下部门的数据，也可以在APP上操作部分管理功能。</p>
                </FormItem>
            </Form> 
      </Modal>
      <Modal  title="选择主管" v-model="modal_select_charge" @on-ok="setSelectedPros" ok-text="保存" cancel-text="放弃操作" class="zh-modal-form">
          <div style="padding:15px 30px">
              <p>从该部门下的运维人员中选择主管。</p>
              <CheckboxGroup v-model="charge"  >
                  <Checkbox v-for="(item,index) in chargeArr" :key="index" :label="JSON.stringify(item)">{{item.name}}</Checkbox>
              </CheckboxGroup>
          </div>
      </Modal>
  </div>
</template>

<script>
import Vue from 'vue'
import util from '@/libs/util.js'
import {saveServicePart,deleteServicePart} from '@/libs/post.js'
import {getSerPart,getSerPartTree,getSerPartPro} from '@/libs/get.js'
export default {
    name:'',
    data () {
        return {
            btnp:{},
            btn:{
                fwsjgou_xzxsbm:false,
                fwsjgou_bj:false,
                fwsjgou_sc:false
            },
            total:0,
            pageSize:10,
            pageNumber:1,
            editLoading:true,
            addLoading:true,
            uuid:'',
            user_type:'',
            userUuid:'',
            modal_add_part:false,
            searchValue:'',
            modal_edit_part:false,
            modal_select_charge:false,
            chargeArr:[{name:'快快快',uuid:'1234567890'}],
            charge:[],
            selectedPros:[],
            superior:'',
            partName:'',
            expand:[],
            proNames:'',
            editPart:{
                uuid:'',     
                proUuid:''
            },
            data:[], 
            columns:[
                {
                    key:'name',
                    title:'部门名称',
                    minWidth:100,
                    render:(h,params)=>{
                        return h('p',{
                            props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#2D8CF0',
                                cursor:'pointer'
                                },
                                on:{
                                    click:()=>{
                                      this.handleClickPartInTable(params.row)
                                    }
                                }
                            },params.row.name)
                        }    
                },{
                    key:'userManager',
                    title:'部门主管',
                    minWidth:100,
                },{
                    key:'count',
                    title:'部门人数',
                    minWidth:100,
                    render:(h,params)=>{
                        return h('Button',{
                            props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#2D8CF0'
                                },
                                on:{
                                    click:()=>{
                                      this.$router.push({name:'operationStaff',params:{}});
                                    }
                                }
                            },`${params.row.count}人`)
                        }    
                },{
                    key:'time',
                    title:'新增时间',
                    minWidth:150
                },{
                    key:'action',
                    title:'操作',
                    align:'center',
                    minWidth:150,
                    fixed:'right',
                    render:(h,params)=>{
                        return h('div',[
                            h('Button',{
                                props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#2D8CF0',
                                display:this.btnp.fwsjgou_bj?'inline-block':'none'
                                },
                                on:{
                                    click:async ()=>{
                                        await this.getPartPros(params.row.uuid);
                                        this.modal_edit_part=true;
                                        this.partName=params.row.name;
                                        
                                        let names=params.row.userManager.length>0?params.row.userManager.split(','):[];
                                        let uuids=params.row.usetUuid.length>0?params.row.usetUuid.split(','):[];
                                        this.editPart.proUuid=uuids;
                                        this.proNames=params.row.userManager;
                                        this.selectedPros=names.map((item,index)=>{
                                            return {
                                                name:item,
                                                uuid:uuids[index]
                                            }
                                        })
                                        this.charge=this.selectedPros.map(item=>{
                                            return JSON.stringify(item)
                                        })
                                       
                                    }
                                }
                            },'编辑'),
                            h('Button',{
                                props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#EA0000',
                                display:this.btnp.fwsjgou_sc?'inline-block':'none'
                                },
                                on:{
                                    click:()=>{
                                        let config={
                                            title:'删除部门',
                                            content:'删除部门后，部门下的人员归属到上一层级下。删除部门不可恢复。',
                                            render:h=>{
                                                return h('div',{
                                                    style:{
                                                        padding:'30px 30px 0 30px',
                                                        textAlign:'left'
                                                    }
                                                },[
                                                    h('p','删除部门后，部门下的人员归属到上一层级下。'),
                                                    h('p','删除部门不可恢复。')
                                                ])
                                            },
                                            okText:'删除',
                                            cancelText:'放弃操作',
                                            onOk:async ()=>{
                                                await this.delete(params.row.uuid)
                                            }
                                        }
                                        this.$Modal.confirm(config) 
                                    }
                                }
                            },'删除'),
                        ])
                    }
                }
            ],  
            tableData:[ ]         
        };
    },
    methods:{
        setSelectedPros(){
            this.selectedPros=this.charge.map(item=>{
                return JSON.parse(item)
            });
            this.proNames=this.selectedPros.map(item=>{
                return item.name
            }).join(',');
            this.editPart.proUuid=this.selectedPros.map(item=>{
                return item.uuid
            }).join(',');

        },
        async delete(uuid){
            let res=await deleteServicePart(uuid);
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:'已删除'
                })
                await this.getTree();
                this.afterAction();
                await this.getPartTable(this.uuid);
                
            }else{
                this.$Notice.error({
                title: '请求出错',
                desc:response.msg
                });
            }
        },
        async save(flag){
            let parentUuid=this.uuid;
            let name=this.partName;
            let proUuid=this.editPart.proUuid;
            let uuid=this.editPart.uuid;
            let res=await saveServicePart({parentUuid,name,uuid,proUuid,flag});
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:'保存成功'
                });
                if(flag=='save'){
                    this.modal_add_part=false;
                }else{
                     this.modal_edit_part=false;
                }
                await this.getTree();
                this.afterAction();
                await this.getPartTable(this.uuid);
                
            }else{
                this.$Notice.error({
                title: '请求出错',
                desc:response.msg
                });
            }
        },
        async handleClickSave(flag){
            if(this.partName.length<=0){
                this.$Notice.error({
                    desc:'请输入部门名称'
                })
            }else if(flag=='save'){
                await this.save(flag);
            }else if(this.editPart.proUuid.length<=0){
                this.$Notice.error({
                    desc:'请选择部门主管'
                })
            }else{
                await this.save(flag);
            }
            if(flag=='save'){
                this.addLoading=false;
                let that=this;
                setTimeout(()=>{
                    that.addLoading=true;
                },500)
                
            }else{
                this.editLoading=false;
                let that=this;
                setTimeout(()=>{
                    that.editLoading=true;
                },500)
            }
            
            
        },
        pageChange(val){
            this.pageNumber=val;
            this.getPartTable(this.uuid);
        },
        async getPartPros(uuid){
            let res=await getSerPartPro(uuid);
            let response=res.data;
            if(response.code===200){
                this.chargeArr=response.data;
            }else{
                this.$Notice.error({
                title: '请求出错',
                desc:response.msg
                });
            }
        },
        async getPartTable(uuid){
            let res=await getSerPart(uuid,this.pageNumber,this.pageSize);
            let response=res.data;
            if(response.code===200){
                this.total=response.data.total;
                this.tableData=response.data.rows.map(item=>{
                    item.time=item.created;
                    return item
                })
            }else{
                this.$Notice.error({
                title: '请求出错',
                desc:response.msg
                });
            }
        },
        toggleExpand(e){
            console.log(e)
            if(e.expand){
                this.expand.push(e.uuid)
            }else{
                this.expand=this.expand.splice(this.expand.indexOf(e.uuid),1)
            }
        },
       
        
        arraction(arr){
            let nArr=arr.map(child=>{
                if(this.expand.includes(child.uuid)){
                    Vue.set(child,'expand',true)
                    //child.expand=true;
                }else{
                    Vue.set(child,'expand',false)
                    //child.expand=false;
                }
                if(child.uuid==this.uuid){
                    Vue.set(child,'selected',true)
                    //child.selected=true;
                }else{
                    Vue.set(child,'selected',false)
                    //child.selected=false;
                }
                if(child.children.length>0){
                    Vue.set(child,'children',this.arraction(child.children))
                    //child.children=this.arraction(child.children)
                }
                return child
            })
            return nArr
        },
        afterAction(){
            this.data=this.data.map(item=>{
                return this.arraction(item)
            })
           
        },
        async selectChange(e){
            this.treeNode=e;
            this.pageNumber=1;
            if(e.length>0){
                this.superior=e[0].name;
                this.uuid=e[0].uuid;
                this.afterAction();
                await this.getPartTable(this.uuid);
                
            }else{
                this.uuid='';
                this.superior="";
                
            }
            
            
        },
        jw(arr){
            let a=[];
            let l=arr.length;
            for(let i=0;i<l;i++){
                a.push(arr[i]);
                if(!!arr[i].children&&arr[i].children.length>0){
                    a=[...a,...this.jw(arr[i].children)]
                }
            }
            return a
        },
        async handleClickPartInTable(obj){
            let a=this.data.map(item=>{
                return this.jw(item)
            });
            let b=[];
            for(let i=0;i<a.length;i++){
                b=[...b,...a[i]]
            }
            let so=b.filter(item=>{
                if(item.uuid==this.uuid){
                    return item
                }
            })[0];
            if(!so.expand){
                this.expand.push(so.uuid);
            }
            await this.selectChange([obj]);
            this.afterAction();
        },
        handleSearch(){
            this.expand=[];
            this.uuid='';
            this.superior="";
            this.pageNumber=1;
            this.getTree();
        },
        async getTree(){
            let res=await getSerPartTree(this.searchValue);
            let response=res.data;
            if(response.code===200){
                this.data=util.TreeFormat(response.data,this.uuid).map(item=>{
                    return [item]
                });
                
            }else{
                this.$Notice.error({
                title: '请求出错',
                desc:response.msg
                });
            }
        }
    },
    created(){
         util.isCustomer(this);
         this.getTree();
         this.btnp=util.bpower(this,this.btn);
    },
    watch:{
        modal_add_part:function(){
            if(!this.modal_add_part){
                this.partName='';
            }
        },
        modal_edit_part:function(){
            if(!this.modal_edit_part){
                this.partName=''
                this.editPart={                   
                    uuid:'',     
                    proUuid:''
                }
            }
        }
    }

}

</script>
<style lang='scss' >

.orgSearch{
    position:relative;
    padding-right:60px;
    .ivu-input{
        width:100%;
    }
    .ivu-btn{
        position:absolute;
        top:0;
        right:0;
    }
}
</style>